package com.ly.hotel.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Environment;
import android.util.Log;

public class FileUtils {
	private String SDPATH;

	private int FILESIZE = 4 * 1024;

	public String getSDPATH() {
		return SDPATH;
	}

	public FileUtils() {
		// 得到当前外部存储设备的目录( /SDCARD )
		SDPATH = Environment.getExternalStorageDirectory() + "/";
	}

	/**
	 * 在SD卡上创建文件
	 * 
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public File createSDFile(String fileName) throws IOException {
		File file = new File(SDPATH + fileName);
		file.createNewFile();
		return file;
	}

	/**
	 * 在SD卡上创建目录
	 * 
	 * @param dirName
	 * @return
	 */
	public File createSDDir(String dirName) {
		File dir = new File(SDPATH + dirName);
		dir.mkdir();
		return dir;
	}

	/**
	 * 判断SD卡上的文件夹是否存在
	 * 
	 * @param fileName
	 * @return
	 */
	public boolean isFileExist(String fileName) {
		File file = new File(SDPATH + fileName);
		return file.exists();
	}

	/**
	 * 将一个InputStream里面的数据写入到SD卡中
	 * 
	 * @param path
	 * @param fileName
	 * @param input
	 * @return
	 */
	public File write2SDFromInput(String path, String fileName, InputStream input) {
		File file = null;
		OutputStream output = null;
		try {
			createSDDir(path);
			file = createSDFile(path + fileName);
			output = new FileOutputStream(file);
			byte[] buffer = new byte[FILESIZE];

			/*
			 * 真机测试，这段可能有问题，请采用下面网友提供的 while((input.read(buffer)) != -1){
			 * output.write(buffer); }
			 */

			/* 网友提供 begin */
			int length;
			while ((length = (input.read(buffer))) > 0) {
				output.write(buffer, 0, length);
			}
			/* 网友提供 end */

			output.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return file;
	}

	//offset 是去掉文件开头的N个字节
	public File write2LocalFromInput(String path, String fileName, InputStream input) {
		File file = null;
		OutputStream output = null;
		try {

			File dir = new File(path);
			dir.mkdir();
			Log.i("interface", "write2LocalFromInput,新建文件:" + path + fileName);
			file = new File(path + fileName);
			output = new FileOutputStream(file);
			byte[] buffer = new byte[FILESIZE];

			/*
			 * 真机测试，这段可能有问题，请采用下面网友提供的 while((input.read(buffer)) != -1){
			 * output.write(buffer); }
			 */

			/* 网友提供 begin */
			int length;
			while ((length = (input.read(buffer))) > 0) {
				output.write(buffer, 0, length);
			}
			/* 网友提供 end */

			output.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return file;
	}

	public File writeInterface2LocalFromInput(String path, String fileName, InputStream input, int offset) {
		File file = null;
		OutputStream output = null;
		int myOffset = 0;
		try {

			File dir = new File(path);
			dir.mkdir();
			Log.i("interface", "write2LocalFromInput,新建文件:" + path + fileName);
			file = new File(path + fileName);
			output = new FileOutputStream(file);
			byte[] buffer = new byte[FILESIZE]; 
			
			byte[] bufferZip = new byte[5*1024*1024];
			int bufferZipLen = 0;//整个文件的大小
			myOffset = offset;
			
			int length;
			//数据全部读取到内存，已经去掉了fuckaishi
			while ((length = (input.read(buffer))) > 0) {
				System.arraycopy(buffer, 0, bufferZip, bufferZipLen ,length);
				bufferZipLen += length;
			}
			
			Log.i("zip", "文件长度:"+ bufferZipLen);
			
			//反转所有数据
//			byte[] tmp = new byte[1];
			byte[] bb = new byte[bufferZipLen-myOffset]; 
			for(int i = bufferZipLen-1; i >= myOffset; i--) { 
//				tmp[0] = bufferZip[i];
				bb[bufferZipLen-1-i] = bufferZip[i];
				//直接写入文件
//				output.write(tmp, 0, 1);
			}
			output.write(bb, 0, bufferZipLen-myOffset);
			/*
			 * 真机测试，这段可能有问题，请采用下面网友提供的 while((input.read(buffer)) != -1){
			 * output.write(buffer); }
			 */


			output.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return file;
	}
	/*删除文件或者目录*/
	public static void deleteFile(File file) {
		if (file.exists()) { // 判断文件是否存在
			if (file.isFile()) { // 判断是否是文件
				file.delete(); // delete()方法 你应该知道 是删除的意思;
			} else if (file.isDirectory()) { // 否则如果它是一个目录
				File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
				for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
					deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
				}
			}
			file.delete();
			Log.i("FileUtil", "删除文件:" + file.getName());
		} else {
			System.out.println("所删除的文件不存在！" + '\n');
		}
	}
	
	//根据文件的路径名，创建该文件的路径
	//失败条件 1.文件已经存在 2.文件的路径没有文件名 3.创建目录失败
	public static boolean createFilePath(String filePathName) {  
        File file = new File(filePathName);  
        if(file.exists()) {  
            Log.i("cloud-download",filePathName + "->目标路径和文件已存在！");  
            return true;  
        }  
        if (filePathName.endsWith(File.separator)) {  
        	Log.i("cloud-download",filePathName + "->失败，目标文件不能为目录！");  
            return false;  
        }  
        //判断目标文件所在的目录是否存在  
        if(!file.getParentFile().exists()) {  
            //如果目标文件所在的目录不存在，则创建父目录  
        	Log.i("cloud-download","目标文件所在目录不存在，准备创建它！");  
            if(!file.getParentFile().mkdirs()) {  
            	Log.i("cloud-download","创建目标文件所在目录失败！");  
                return false;  
            }else{
            	Log.i("cloud-download","创建目标文件所在目录成功！");  
            	return true; 
            }  
        }else{
        	Log.i("cloud-download","目标文件所在目录存在，不需要创建！");
        	return true;
        }  

    }  
	
	//解析路径中的文件名，正确就返回文件名，错误就返回空
	public static String getFileName(String path,boolean suffix){
		String fileName = null;
		
		File tempFile = new File(path.trim());  
         
	    fileName = tempFile.getName();  
	    
	    if(fileName != null){
	    	if(suffix && fileName.contains(".")){
//	    		Log.i("cloud-download","getFileName = " + fileName);   
	    	}else if(!suffix){
//	    		Log.i("cloud-download","getFileName = " + fileName);  
	    	}else{
	    		Log.i("cloud-download","getFileName：获取文件名失败");  
	    	}
	    }
	    
		
		return fileName;
	}
	
	public static boolean isFileExists(String filePathName) {  
        File file = new File(filePathName);  
        if(file.exists()) {  
            return true;  
        } else {
        	return false; 
        }
	}
}
